package com.navi168.fwq21.hyzl;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.SearchRecentSuggestions;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.amap.mapapi.core.AMapException;
import com.amap.mapapi.core.GeoPoint;
import com.amap.mapapi.core.PoiItem;
import com.amap.mapapi.geocoder.Geocoder;
import com.amap.mapapi.location.LocationManagerProxy;
import com.amap.mapapi.location.LocationProviderProxy;
import com.amap.mapapi.map.MapActivity;
import com.amap.mapapi.map.MapController;
import com.amap.mapapi.map.MapView;
import com.amap.mapapi.map.PoiOverlay;
import com.amap.mapapi.poisearch.PoiSearch;
import com.navi168.fwq21.R;
import com.navi168.fwq21.db.Sqlh;
import com.navi168.fwq21.hyzl.mod.MypoiItems;
import com.navi168.fwq21.util.MySuggestionProvider;
import com.navi168.fwq21.util.Constants;

public class ShowMap extends MapActivity {
	private static final String SPF = "NAVI168";
	private MapView mapView;
	private MapController mMapController;
	private LocationManagerProxy mLocationManager;
	private GeoPoint point;
	private EditText inputText;
	private String query = null;
	private Sqlh sqlh;
	private Spinner provinceSpinner;
	private ArrayList<MypoiItems> mypoiItems = new ArrayList<MypoiItems>();
	private ArrayList<PoiItem> poiItems = new ArrayList<PoiItem>();
	private PoiOverlay poiOverlay;
	private int point_show;
	private Spinner citySpinner;
	private String cityString;
	private Geocoder geocoder;
	private List<Address> address;
	private ProgressDialog progDialog;
	private Button ssfs_button;
	private Button getloc_button;
	private Button xqlb_butButton;
	private int mylat = 0;// 当前纬度
	private int mylog = 0;// 当前经度
	private final String[] mItems = { "使用我的位置", "选取地图上的点", "兴趣列表选择", "历史记录选择",
			"切换城市" };
	private boolean gps_flag;// 可否定位开关
	private MyLocationOverlayProxy mLocationOverlay;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showmap);
		sqlh = sqlh.getInstance(ShowMap.this);
		progDialog = new ProgressDialog(this);
		geocoder = new Geocoder(this);
		findViews();
		setListers();
		SharedPreferences settings = getSharedPreferences(SPF,
				MODE_WORLD_READABLE);
		gps_flag = settings.getBoolean("auto_loc", true);
		point = new GeoPoint(
				settings.getInt("city_lat", (int) (31.18334 * 1E6)),
				settings.getInt("city_long", (int) (121.43348 * 1E6)));
		mapView.setBuiltInZoomControls(true);
		mMapController = mapView.getController();
		mMapController.setCenter(point); // 设置地图中心点
		mMapController.setZoom(13);

		// 定位初始化
		if (gps_flag) {
			locationInit();
		}

	}

	private void locationInit() {
		// 定位初始化
		mLocationOverlay = new MyLocationOverlayProxy(ShowMap.this, mapView);
		// mLocationOverlay.enableMyLocation();
		mapView.getOverlays().add(mLocationOverlay);
		mLocationOverlay.runOnFirstFix(new Runnable() {
			public void run() {
				handler.sendMessage(Message.obtain(handler,
						Constants.FIRST_LOCATION));
				Log.i("mylog", "runonfirstfix!");
			}
		});

	}

	private void findViews() {

		mLocationManager = LocationManagerProxy.getInstance(this);
		mapView = (MapView) findViewById(R.id.poisearch_MapView);
		ssfs_button = (Button) findViewById(R.id.ssfs_button);
		inputText = (EditText) findViewById(R.id.input_showmap);
		inputText.setCursorVisible(false);
		inputText.setInputType(InputType.TYPE_NULL);
		getloc_button = (Button) findViewById(R.id.dw_button);
		xqlb_butButton = (Button) findViewById(R.id.xqlb_button);

	}

	/**
	 * 
	 * 功能：注册所有按键的监听 void
	 * 
	 */
	private void setListers() {
		getloc_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				openGps();

			}
		});
		inputText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.i("mylog", "input onclick!");
				onSearchRequested();

			}
		});
		ssfs_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 弹出搜索方式对话框
				showDialog(1);
			}
		});
		xqlb_butButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				//
				Intent intent = new Intent(ShowMap.this, SomeList.class);
				// startActivity(intent);
				startActivityForResult(intent, Constants.FAVO_FLAG);

			}
		});

	}

	private void showToast(String showString) {
		Toast.makeText(getApplicationContext(), showString, Toast.LENGTH_SHORT)
				.show();
	}

	@Override
	public void onNewIntent(final Intent newIntent) {
		super.onNewIntent(newIntent);
		String ac = newIntent.getAction();
		Log.i("mylog", "!!!!!");
		if (Intent.ACTION_SEARCH.equals(ac)) {
			doSearchQuery(newIntent);
		}
	}

	private void doSearchQuery(Intent intent) {
		query = intent.getStringExtra(SearchManager.QUERY);
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
				ShowMap.this, MySuggestionProvider.AUTHORITY,
				MySuggestionProvider.MODE);
		suggestions.saveRecentQuery(query, null);
		Intent poIntent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putString("query_key", query);
		poIntent.putExtras(bundle);
		poIntent.setClass(ShowMap.this, PoiList.class);
		startActivity(poIntent);
	}

	@Override
	protected void onResume() {
		mypoiItems = getIntent().getParcelableArrayListExtra("poilists");// 获取poi结果集
		point_show = getIntent().getIntExtra("point_show", 0);

		if (mypoiItems != null) {

			for (MypoiItems mypoiItem : mypoiItems) {
				GeoPoint gPoint = new GeoPoint(mypoiItem.getLatit(),
						mypoiItem.getLongit());
				PoiItem poiItem = new PoiItem(mypoiItem.getId(), gPoint,
						mypoiItem.getSnippet(), mypoiItem.getTitle());
				poiItems.add(poiItem);
			}
			Log.i("mylog", point_show + "%%%%");
			Log.i("mylog", mypoiItems.size() + "%%%%");
			mMapController.setZoom(15);
			mMapController.animateTo(poiItems.get(point_show).getPoint());

			if (poiOverlay != null) {
				poiOverlay.removeFromMap();
			}
			Drawable drawable = getResources().getDrawable(
					R.drawable.da_marker_red);
			poiOverlay = new MyPoiOverlay(ShowMap.this, drawable, poiItems,
					mapView); // 将结果的第一页添加到PoiOverlay
			poiOverlay.addToMap(mapView); // 将poiOverlay标注在地图上
			poiOverlay.showPopupWindow(point_show);
		}

		this.mLocationOverlay.enableMyLocation();
		super.onResume();
	}

	@Override
	protected void onPause() {
		this.mLocationOverlay.disableMyLocation();
		super.onPause();
	}

	private String findCity() {
		SharedPreferences settings = getSharedPreferences(SPF,
				MODE_WORLD_READABLE);
		String cityString = settings.getString("city_now", "");

		return cityString;

	}

	/**
	 * 
	 * 功能：返回省份
	 * 
	 * @return SpinnerAdapter
	 */
	private SpinnerAdapter getP() {
		SpinnerAdapter adapter = sqlh.getProvince(ShowMap.this);
		return adapter;
	}

	/**
	 * 
	 * 功能：返回省份下的城市
	 * 
	 * @param id
	 * @return SpinnerAdapter
	 */
	private SpinnerAdapter getC(long id) {
		SpinnerAdapter adapter = sqlh.getCity(ShowMap.this, String.valueOf(id));
		return adapter;
	}

	private void loadSpinner() {

		provinceSpinner.setPrompt("请选择省份");
		provinceSpinner.setAdapter(getP());
		provinceSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				citySpinner.setPrompt("请选择城市");
				citySpinner.setAdapter(getC(arg3));

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		citySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				cityString = sqlh.getCityName(arg3);

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateDialog(int) 生成城市选择对话框
	 */
	@Override
	protected Dialog onCreateDialog(int id) {

		AlertDialog.Builder builder = new Builder(this);
		if (id == 0) { // 获取布局相关的对象
			LayoutInflater inflater = LayoutInflater.from(this);
			// 获取相关的布局
			View layout = inflater.inflate(R.layout.chosecity, null);
			provinceSpinner = (Spinner) layout.findViewById(R.id.province);
			citySpinner = (Spinner) layout.findViewById(R.id.city);
			loadSpinner();

			// 设置相关的视图

			builder.setView(layout);
			// 设置标题
			builder.setTitle("选择城市");
			// 确定按钮的操作
			builder.setPositiveButton("确认",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {

							Thread thread = new Thread(new Runnable() {

								@Override
								public void run() {

									try {

										address = geocoder.getFromLocationName(
												cityString, 3);
										Log.i("mylog",
												"address" + address.size());
										if (!address.isEmpty()) {
											handler.sendMessage(Message.obtain(
													handler,
													Constants.GEOCODER_RESULT));
											// TODO 加入切换后的城市
											SharedPreferences.Editor editor = getSharedPreferences(
													SPF, MODE_PRIVATE).edit();
											editor.putString("city_now",
													cityString);
											editor.putInt(
													"city_lat",
													(int) (address.get(0)
															.getLatitude() * 1E6));
											editor.putInt(
													"city_long",
													(int) (address.get(0)
															.getLongitude() * 1E6));
											editor.commit();

										}

									} catch (AMapException e) {
										Log.i("mylog", "getFromLocationName:"
												+ e.toString() + "--"
												+ cityString);
										e.printStackTrace();
										handler.sendMessage(Message.obtain(
												handler, Constants.ERROR));
									}
								}
							});

							dialog.dismiss();

							progDialog
									.setProgressStyle(ProgressDialog.STYLE_SPINNER);
							progDialog.setIndeterminate(false);
							progDialog.setCancelable(true);
							progDialog.setMessage("切换城市中...");
							progDialog.show();
							thread.start();

						}
					});
			// 取消按钮的操作
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

							dialog.dismiss();

						}
					});
		} else
		// 自定义对话框
		if (id == 1) {
			LayoutInflater inflater = LayoutInflater.from(this);
			// 获取相关的布局
			View layout = inflater.inflate(R.layout.ssfs_dailog, null);
			builder.setView(layout);
			// 设置标题
			builder.setTitle("选择搜索方式");
			// 确定按钮的操作
			builder.setItems(mItems, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					// 点击后弹出窗口选择了第几项
					// showToast("你选择的id为" + which + " , " + mItems[which]);
					if (which == 4) {
						dialog.dismiss();
						showDialog(0);
					}

					if (which == 0) {

						dialog.dismiss();
						if (gps_flag) {
							localPoiSearch();
						} else {
							showToast("自动定位已关闭，请进入设置中打开");
						}

					}
					
					if (which == 2||which==3) {
						Intent intent = new Intent(ShowMap.this, SomeList.class);
						startActivityForResult(intent, Constants.FAVO_FLAG);
					}

				}

			});

		}

		return builder.create();
	}

	private void localPoiSearch() {
		// TODO 向poilist发送经纬度和搜索方式名称
		String searchtype = "当前位置";
		Bundle bundle = new Bundle();
		bundle.putInt("lat", mylat);
		bundle.putInt("long", mylog);
		bundle.putString("searchtype", searchtype);
		Intent intent = new Intent();
		intent.putExtras(bundle);
		intent.setClass(ShowMap.this, NearPoi.class);
		startActivity(intent);

	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == Constants.FIRST_LOCATION) {
				mMapController.animateTo(mLocationOverlay.getMyLocation());
				mylat = mLocationOverlay.getMyLocation().getLatitudeE6();
				mylog = mLocationOverlay.getMyLocation().getLongitudeE6();
				// Log.i("mylog",
				// mLocationOverlay.getMyLocation().getLatitudeE6()
				// + "--"
				// + mLocationOverlay.getMyLocation().getLongitudeE6());
			}
			if (msg.what == Constants.GEOCODER_RESULT) {
				progDialog.dismiss();
				double lat = address.get(0).getLatitude() * 1E6;
				double lont = address.get(0).getLongitude() * 1E6;
				Log.i("mylog", "lat:" + lat);
				mMapController.setZoom(11);
				mMapController.setCenter(new GeoPoint((int) lat, (int) lont));
			}

		}
	};

	private void openGps() {

		if (startListening()) {
			if (mLocationOverlay.getMyLocation() != null) {
				mMapController.animateTo(mLocationOverlay.getMyLocation());
				mylat = mLocationOverlay.getMyLocation().getLatitudeE6();
				mylog = mLocationOverlay.getMyLocation().getLongitudeE6();
			}

		} else {
			Intent intent = new Intent(
					android.provider.Settings.ACTION_SECURITY_SETTINGS);
			startActivity(intent);

		}

	}

	public boolean startListening() {
		boolean result = false;
		// 获取当前可用的Provider,其中MapABCNetwork为MapABC网络定位(基站和WiFi)
		for (final String provider : mLocationManager.getProviders(true)) {
			if (LocationManagerProxy.GPS_PROVIDER.equals(provider)
					|| LocationProviderProxy.MapABCNetwork.equals(provider)) {
				Log.i("mylog", "provider:" + provider);
				result = true;

			}
		}
		return result;
	}

	@Override
	protected void onStop() {
		if (sqlh.getC() != null) {
			Log.i("mylog", "c is not null");
			sqlh.getC().close();
			Log.i("mylog", "c is close");
		}
		super.onStop();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case 1://如果是1将返回的点在地图上显示出来。
			MypoiItems mypoiitem = (MypoiItems) data
					.getParcelableExtra("poiitem");
			GeoPoint gPoint = new GeoPoint(mypoiitem.getLatit(),
					mypoiitem.getLongit());
			PoiItem poiItem = new PoiItem(mypoiitem.getId(), gPoint,
					mypoiitem.getSnippet(), mypoiitem.getTitle());
			poiItems.add(poiItem);
			mMapController.setZoom(15);
			mMapController.animateTo(poiItems.get(0).getPoint());

			if (poiOverlay != null) {
				poiOverlay.removeFromMap();
			}
			Drawable drawable = getResources().getDrawable(
					R.drawable.da_marker_red);
			poiOverlay = new MyPoiOverlay(ShowMap.this, drawable, poiItems,
					mapView); // 将结果的第一页添加到PoiOverlay
			poiOverlay.addToMap(mapView); // 将poiOverlay标注在地图上
			poiOverlay.showPopupWindow(0);

			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);

	}

}
